<template>
	<view class="task-progress-wrap">
		<uv-navbar title="任务进度" bg-color="rgba(0,0,0,.0)" :placeholder='true' leftIconSize="20px"
			leftIconColor="#313C56" rightText="" rightIconColor="#313C56" :autoBack='true'
			titleStyle="font-size: 16px;font-weight: 500;color: #313c56;" />
		<view class="task-progress-header">
			<view class="title">
        {{ info.name }}
			</view>
      总金额: {{info.totalAmount}} USDT
			<view class="tip">
        合作对象正在努力完成任务...
			</view>
		</view>
		<view class="scroll-wrap" style="height: calc(100% - 178px);">
      <scroll-view class="scroll" :scroll-y="true">
				<view class="box base-info flex-row flex-between flex-items-center">
					<image class="avatar" :src="info.head" mode=""> </image>
					<view class="info">
						<view class="name flex-row flex-items-center">
							{{info.bossName}}
              <image class="grade" v-if="info.level === 0" src="../../static/user/b0.png" style="margin-left: 3px; width: 30px; min-width: 30px; max-width: 30px;" mode="widthFix"></image>
              <image class="grade" v-if="info.level === 1" src="../../static/user/b1.png" style="margin-left: 3px; width: 30px; min-width: 30px; max-width: 30px;" mode="widthFix"></image>
              <image class="grade" v-if="info.level === 2" src="../../static/user/b2.png" style="margin-left: 3px; width: 30px; min-width: 30px; max-width: 30px;" mode="widthFix"></image>
              <image class="grade" v-if="info.level === 3" src="../../static/user/b3.png" style="margin-left: 3px; width: 30px; min-width: 30px; max-width: 30px;" mode="widthFix"></image>
              <image class="grade" v-if="info.level === 4" src="../../static/user/b4.png" style="margin-left: 3px; width: 30px; min-width: 30px; max-width: 30px;" mode="widthFix"></image>
              <image class="grade" v-if="info.level === 5" src="../../static/user/b5.png" style="margin-left: 3px; width: 30px; min-width: 30px; max-width: 30px;" mode="widthFix"></image>
						</view>
						<view class="button" @click="teamDetails(info.bossType, info.bossId)">查看主页</view>
					</view>
					<image class="message" src="../../static/message.png" mode=""></image>
				</view>

				<view class="deliver-list">
					<view class="box-item" v-for="(item, index) in info.plans" :key="index">
						<view class="title">
							第 {{ index + 1 }} 期 -
              {{ item.amount }} USDT - {{ item.rate }}
						</view>
						<view class="deadline">
							截止时间：{{item.endTime}}
						</view>
            <view class="timeout" v-if="item.delay == 1 && item.status == 0">
              已超时，请与合作对象沟通
            </view>

            <view class="empty flex-row flex-column flex-center flex-items-center" v-if="item.status == 0">
              <image src="../../static/empty.png" mode=""></image>
              <view class="text">
                等待合作对象上传
              </view>
            </view>

						<view  class="button-wrap flex-row flex-center flex-items-center" v-if="item.payStatus == 0">
							<view :class="`deliver-button flex-row flex-center flex-items-center ${item.payStatus == 0 && 'active'}`" @click="planPay(item)">
								待支付
							</view>
						</view>

						<view class="deliver-info" v-if="item.status == 1 || item.status == 2">
							<view class="list-header flex-row flex-items-center">
								图片
							</view>
							<view class="img-list">
								<image v-for="(img, index) in item.pics" :src="img" mode="" @click="previewImage(item.pics, index)"> </image>
							</view>
							<view class="list-header flex-row flex-items-center">
								附件
							</view>
							<view class="file-box flex-row flex-between flex-items-center"  v-for="(document, index) in item.documents" :key="index">
								<image class="icon" src="../../static/file-icon.png" mode=""></image>
								<view class="content">
									<view class="name">
										{{document.name}}
									</view>
								</view>
								<image class="download" src="../../static/download.png" mode="" @click="download(document.detailUrl)"></image>
							</view>

							<view class="list-header flex-row flex-items-center">
								上传时间
							</view>

							<view class="time-wrap">
								<view class="time">
									上传时间：{{item.time}}
								</view>
								<view v-if="item.status == 1" class="btn flex-row flex-center flex-items-center" @click="planDislodge(item)">
									确认交付
								</view>
							</view>
						</view>

					</view>
				</view>

        <view class="stop-button-wrap">
          <view class="stop-button flex-row flex-center flex-items-center">
            终止项目
          </view>
        </view>
			</scroll-view>
		</view>

<!--		<view  class="toolbar" :style="{height: $uv.addUnit(toolbarHeight)}">-->
		<view  class="toolbar">
			<view class="flex-row flex-center flex-items-center" style="width:100%; height: 28px; ">
				<view v-if="info.evaluable" class="button flex-row flex-center flex-items-center" @click="">
					完成任务
				</view>
				<view v-if="info.evaluable" class="button flex-row flex-center flex-items-center" @click="">
					评价
				</view>
			</view>
		</view>

		<toast ref="toast"></toast>
	</view>

</template>

<script>
import {planPay, planSubmit, progressDetail} from "../../api";
	export default {
		data() {
			return {
        project: 0,
				info: {},
        // 主网
        spxContractAddr: '0x212fACFf93f0830Ed39229fa55615173C3AC98C5', // spx 合约地址
        usdtContractAddr: '0x55d398326f99059fF775485246999027B3197955', // usdt 代币地址
        abi: [
          // erc 20
          'function name() public view returns (string memory)', //  name
          'function symbol() public view returns (string memory)', // 代币
          'function decimals() external view returns (uint8)', // 单位
          'function initialSupply() external view returns (uint256)', // 初始发行量
          'function totalSupply() external view returns (uint256)', // 总供给
          'function balanceOf(address account) external view returns (uint256)', // 获取余额
          'event Transfer(address indexed from, address indexed to, uint256 value)', // 转账事件
          'function approve(address spender, uint256 amount) public returns (bool)', // 授权
          // 合约
          'function liquidityMint() public returns (bool)', // LP提取
          'function getLpClaim(address account) public view returns (uint256)', // 查询 LP 可提取余额
          'function buyNFTCard(uint256 amountRora, uint256 amountUsd, uint256 random) public returns (bool)', // 购买
          // spx 相关 1, 铸造获取身份 2, 发布任务 3, 确认支付
          'function mintNft(uint256 mint) public returns (bool)',
          'function publish(address nomad, uint256 amount, uint256 stage, uint256 random) public returns (bool)',
          'function dislodge(uint256 random, address nomad) public returns (bool)',
        ],
			};
		},
    computed: {
      toolbarHeight() {
        const sys = uni.$uv.sys()
        return sys.safeAreaInsets.bottom + 50
      }
    },
    onLoad(info) {
      this.project = info.id
    },
    mounted() {
      this.show()
    },

    methods: {
      previewImage(url, index) {
        uni.previewImage({
          urls: url,
          current: index
        })
      },
      download(url) {
        // #ifdef H5
        window.location.href=url
      },
      show() {
        this.getProject()
      },
      getProject() {
        let params = {
          type: 1,
          id: this.project,
        }
        progressDetail(params).then((data) => {
          this.info = data
          console.error(this.info)
        }).catch((e) => {
        })
      },

      async planDislodge(item) {
        uni.showLoading({
          title: '交付中,请等待...',
          mask:true
        })
        try {
          let planId = item.planId;
          let digitalAddr = item.digitalAddr;
          let payRandom = item.payRandom;
          await this.dislodge_(payRandom, digitalAddr);
          await this.projectSubmit_(planId);
        }catch (error){
          this.$refs.toast.show({msg: '交付失败!'})
        }
        setTimeout(function() {
          uni.hideLoading()
        }, 50)
      },

      async planPay(item) {
        uni.showLoading({
          title: '支付中,请等待...',
          mask:true
        })
        try {
          let digitalAddr = item.digitalAddr;
          let amount = item.amount;
          let plan = item.plan;
          let planId = item.planId;
          let now = new Date().getTime() // 1669514448542
          await this.approveUsdt(amount);
          await this.publish_(digitalAddr, amount, plan, now);
          await this.projectPay_(now, planId);
        }catch (error){
          this.$refs.toast.show({msg: '支付失败!'})
        }
        setTimeout(function() {
          uni.hideLoading()
        }, 50)
      },

      // Usdt 转账
      async transferUsdt(to, amountUsdt) {
        const amountUsdtWei = this.$web3.utils.parseEther(amountUsdt.toString());
        const tc = await this.$web3.getSingerContract(this.usdtContractAddr, this.abi);
        return await tc.transfer(to, amountUsdtWei);
      },

      // 发布任务合约支付
      async dislodge_(random, addr) {
        const tc = await this.$web3.getSingerContract(this.spxContractAddr, this.abi);
        return await tc.dislodge(random, addr);
      },

      // 发布任务合约支付
      async publish_(nomad, amount, stage, random) {
        const amountUsdWei = this.$web3.utils.parseEther(amount.toString());
        const tc = await this.$web3.getSingerContract(this.spxContractAddr, this.abi);
        return await tc.publish(nomad, amountUsdWei, stage, random);
      },

      // 授权 Usdt
      async approveUsdt(amountUsd) {
        const amountUsdWei = this.$web3.utils.parseEther(amountUsd.toString());
        const usdtTc = await this.$web3.getSingerContract(this.usdtContractAddr, this.abi);
        const tr = await usdtTc.approve(this.spxContractAddr, amountUsdWei);
        await tr.wait();
      },

      async projectPay_(payRandom, planId) {
        let params = {
          planId: planId,
          payRandom: payRandom
        }
        await planPay(params).then((data) => {
          this.$refs.toast.show({
            msg: '支付成功!',
            isSuccees: true
          })
          setTimeout(() => {
            this.show()
          }, 1000);
        }).catch((res) => {})
      },

      async projectSubmit_(planId) {
        let params = {
          planId: planId
        }
        await planSubmit(params).then((data) => {
          this.$refs.toast.show({
            msg: '交付成功!',
            isSuccees: true
          })
          setTimeout(() => {
            this.show()
          }, 1000);
        }).catch((res) => {})
      },


      /**
       * 公司详情跳转
       */
      teamDetails(type, id) {
        if (type == 3){
          uni.navigateTo({
            url: '/pages/person-detail/person-detail?userId=' + id + "&sys=0"
          })
        } else {
          uni.navigateTo({
            url: '/pages/company-detail/company-detail?id=' + id
          })
        }
      },
    }
	}
</script>

<style lang="scss" scoped>
	.task-progress-wrap {
		background: url(/static/progress-bg.png) top left;
		background-size: 100% 400px;
		background-repeat: no-repeat;
		display: flex;
		height: 100vh;
		width: 100vw;
		flex-direction: column;
		background-color: #F4F7FD;
		overflow: hidden;

		.task-progress-header {
			margin: 12px;

			.title {
				font-size: 18px;
				font-weight: 600;
				color: #313C56;
			}

			.tip {
				height: 16px;
				margin-top: 4px;
				font-size: 12px;
				color: #6B7885;
			}
		}

		.scroll-wrap {
			padding: 0 12px;
			box-sizing: border-box;

			.scroll {
				width: 100%;
				border-radius: 12px;
				height: 100%;

				.base-info {
					padding: 12px;
					height: 66px;
					background-color: #fff;
					border-radius: 12px;

					.avatar {
						width: 40px;
						height: 40px;
					}

					.info {
						flex: 1;
						margin: 0 16px;

						.name {
							font-size: 16px;
							color: #313C56;

							.grade {
								margin-left: 4px;
								width: 18px;
								height: 18px;
							}
						}

						.button {
              margin-bottom: 4px;
							margin-top: 4px;
							font-size: 12px;
							color: #EB7520;
						}
					}

					.message {
						width: 18px;
						height: 18px;
					}
				}

				.deliver-list {
					.box-item {
						box-sizing: border-box;
						background-color: #fff;
						border-radius: 12px;
						margin-top: 12px;
						height: auto;
						padding: 16px;
						width: 100%;

						.title {
							font-size: 16px;
							color: #313C56;
						}

						.deadline {
							font-size: 12px;
							color: #6B7885;
						}

						.deliver-info {

							.list-header {
								font-size: 14px;
								color: #313C56;
								margin: 12px 0 4px;

								&::before {
									content: '';
									height: 10px;
									width: 2px;
									background: #EB7520;
									border-radius: 2px;
									margin-right: 4px;
								}
							}

							.img-list {
								image {
									width: 80px;
									height: 80px;
									border-radius: 6px;
									margin-right: 12px;
								}
							}

							.file-box {
								height: 72px;
								border: 1px solid #EFF0F4;
								border-radius: 8px;
								padding: 0 16px;

								.icon {
									width: 36px;
									height: 36px;
								}

								.content {
									margin: 0 4px 0 12px;
									flex: 1;

									.name {
										font-size: 14px;
										color: #313C56;
									}

									.size {
										font-size: 14px;
										color: #6B7885;
									}
								}

								.download {
									width: 16px;
									height: 16px;
								}
							}

							.time-wrap {
								position: relative;

								.time {
									font-size: 12px;
									color: #6B7885;
									margin: 4px 0 48px;
								}

								.btn {
									position: absolute;
									right: 0;
									top: 20px;
									width: 128px;
									height: 36px;
									background: #EB7520;
									box-shadow: 0px 1px 2px 0px rgba(16, 24, 40, 0.05);
									border-radius: 80px 80px 80px 80px;
									font-size: 14px;
									color: #FFFFFF;
								}

								.update {
									position: absolute;
									right: 0;
									top: 20px;
									width: 56px;
									height: 36px;
									background: #FFFFFF;
									box-shadow: 0px 1px 2px 0px rgba(16, 24, 40, 0.05);
									border-radius: 80px 80px 80px 80px;
									font-size: 14px;
									color: #344054;
									border: 1px solid rgba(16, 24, 40, 0.05);
								}
							}
						}

						.button-wrap {
							padding: 20px 0 8px;

							.deliver-button {
								width: 128px;
								height: 36px;
								background: #FBDED2;
								box-shadow: 0px 1px 2px 0px rgba(16, 24, 40, 0.05);
								border-radius: 80px 80px 80px 80px;
								font-size: 14px;
								color: #FFFFFF;

								&.active {
									background: #EB7520;
								}
							}
						}

						.timeout {
							font-size: 12px;
							color: #D82D2D;
						}

						.empty {
							image {
								width: 80px;
								height: 80px;
								margin: 12px 0 4px;
							}

							.text {
								font-size: 12px;
								color: #95A4B3;
							}
						}
					}
				}

				.stop-button-wrap {
					padding: 12px 0 16px;

					.stop-button {
						background: #fff;
						margin-top: 12px;
            width: 100%;
						height: 44px;
						border-radius: 80px;
						font-size: 16px;
						color: #313C56;
					}
				}
			}
		}


		.toolbar {
			height: 10px;
			width: 100%;
			background: #FFFFFF;
			border-radius: 24px 24px 0px 0px;
			box-sizing: border-box;
			font-size: 16px;
			color: #fff;

			.button {
				width: 303px;
				height: 44px;
				background: #EB7520;
				box-shadow: 0px 1px 2px 0px rgba(16, 24, 40, 0.05);
				border-radius: 80px 80px 80px 80px;
			}
		}


	}
</style>